/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.authority.controller;

import com.wallellen.authority.AuthUtils;
import com.wallellen.authority.domain.Organization;
import com.wallellen.authority.service.OrganizationServiceInterface;
import com.wallellen.core.page.OperateType;
import com.wallellen.core.page.RequestMode;
import com.wallellen.core.page.ViewMode;
import com.wallellen.core.sql.query.DBRule;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.result.DataResult;
import com.wallellen.web.WebUtils;
import com.wallellen.web.easy.EasyUiTreeNode;
import com.wallellen.web.easy.EasyUiUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by walle on 12/12/15.
 */

@RequestMapping({"/organization"})
@Controller
public class OrganizationController extends WebUtils {
    private static final Logger log = LoggerFactory.getLogger(OrganizationController.class);

    @Resource
    OrganizationServiceInterface organizationServiceImpl;

    public OrganizationServiceInterface getOrganizationServiceImpl() {
        return this.organizationServiceImpl;
    }

    public void setOrganizationServiceImpl(OrganizationServiceInterface organizationServiceImpl) {
        this.organizationServiceImpl = organizationServiceImpl;
    }

    @RequestMapping({"/query"})
    @ResponseBody
    public Map<String, Object> queryall(@ModelAttribute("query") DataQuery query, HttpServletRequest request) {
        try {
            query = EasyUiUtils.formatGridQuery(request, query);
            if (query.getQueryRule().size() == 0) {
                query.addRule(new DBRule("PARENTID", "NONE", "="));
            }
            DataResult result = this.organizationServiceImpl.createOrganizationSimpleQuery(query).search();
            result.runDictionary("1:可用,0:禁用", "STATE");
            result.runDictionary("1:标准", "TYPE");
            return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/list"})
    public ModelAndView index(HttpSession session) {
        return ViewMode.getInstance().returnModelAndView("authority/OrganizationResult");
    }

    @RequestMapping({"/chooseOrg"})
    public ModelAndView chooseOrg(HttpSession session) {
        return ViewMode.getInstance().returnModelAndView("authority/ChooseOrgResult");
    }

    @RequestMapping({"/organizationTabs"})
    public ModelAndView orgTabs(RequestMode pageset, String ids, String parentID) {
        if (pageset.getOperateType() == 1) {
            return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("parentId", parentID)
                    .returnModelAndView("authority/OrganizationTabs");
        }
        Organization entity = this.organizationServiceImpl.getOrganizationEntity(ids);
        return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", entity)
                .putAttr("parentId", entity.getParentid()).putAttr("ids", ids)
                .returnModelAndView("authority/OrganizationTabs");
    }

    @RequestMapping({"/postConsoleTabs"})
    public ModelAndView postConsoleTabs(RequestMode pageset, String ids) {
        return ViewMode.getInstance().putAttr("pageset", pageset).returnModelAndView("authority/PostResult");
    }

    @RequestMapping({"/postActionsTabs"})
    public ModelAndView postActionsTabs(RequestMode pageset, String ids) {
        return ViewMode.getInstance().putAttr("pageset", pageset).returnModelAndView("authority/OrgUserResult");
    }

    @RequestMapping({"/OrgTreeNodeSubmit"})
    @ResponseBody
    public Object moveTreeNodeSubmit(String ids, String id) {
        try {
            this.organizationServiceImpl.moveOrgTreeNode(ids, id);
            return ViewMode.getInstance().returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/edit"})
    @ResponseBody
    public Map<String, Object> editSubmit(Organization org, HttpSession session) {
        try {
            Organization entity = this.organizationServiceImpl.editOrganizationEntity(org, getCurrentUser(session));
            return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/add"})
    @ResponseBody
    public Map<String, Object> addSubmit(Organization org, HttpSession session) {
        try {
            Organization entity = this.organizationServiceImpl.insertOrganizationEntity(org, getCurrentUser(session));
            return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/del"})
    @ResponseBody
    public ModelAndView delSubmit(String ids, HttpSession session) {
        try {
            for (String id : parseIds(ids)) {
                this.organizationServiceImpl.deleteOrganizationEntity(id, getCurrentUser(session));
            }
            return ViewMode.getInstance().returnModelAndView("authority/OrganizationResult");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnModelAndView("authority/OrganizationResult");
        }
    }

    @RequestMapping({"/removePostUser"})
    @ResponseBody
    public ModelAndView removePostUserSubmit(String id, String ids, HttpSession session) {
        try {
            this.organizationServiceImpl.removePostUsers(id, ids, getCurrentUser(session));
            return ViewMode.getInstance().returnModelAndView("authority/OrgUserResult");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnModelAndView("authority/OrgUserResult");
        }
    }

    @RequestMapping({"/orgTreeNodeTreeView"})
    public ModelAndView forSend(String ids) {
        return ViewMode.getInstance().putAttr("ids", ids)
                .returnModelAndView("authority/OrganizationTreenodeChooseTreeWin");
    }

    @RequestMapping({"/userORGTreeView"})
    public ModelAndView userOrgTree(String ids) {
        return ViewMode.getInstance().putAttr("ids", ids).returnModelAndView("authority/UserorgChooseTreeWin");
    }

    @RequestMapping({"/userOrg"})
    @ResponseBody
    public Object userORGSubmit(RequestMode pageset, String ids, String id, HttpSession session) {
        try {
            for (String userId : parseIds(ids)) {
                this.organizationServiceImpl.addUserPost(userId, id, getCurrentUser(session));
            }
            return ViewMode.getInstance().returnObjMode();
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/postTree"})
    @ResponseBody
    public Object userORGLoadTree(String id) {
        return this.organizationServiceImpl.loadPostTree(id);
    }

    @RequestMapping({"/form"})
    public ModelAndView view(RequestMode pageset, String ids, String parentId) {
        try {
            Organization parent = null;

            if ((!parentId.equals("")) && (parentId != null)) {
                parent = this.organizationServiceImpl.getOrganizationEntity(parentId);
            }

            Organization entity = null;

            switch (pageset.getOperateType()) {
                case 1:
                    return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("parent", parent)
                            .returnModelAndView("authority/OrganizationForm");
                case 0:
                    entity = this.organizationServiceImpl.getOrganizationEntity(ids);
                    return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", entity)
                            .putAttr("parent", parent).returnModelAndView("authority/OrganizationForm");
                case 2:
                    entity = this.organizationServiceImpl.getOrganizationEntity(ids);
                    return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", entity)
                            .putAttr("parent", parent).returnModelAndView("authority/OrganizationForm");
            }
        } catch (Exception e) {
            return ViewMode.getInstance().setError(e + e.getMessage()).returnModelAndView("authority/OrganizationForm");
        }
        return ViewMode.getInstance().returnModelAndView("authority/OrganizationForm");
    }

    @RequestMapping({"/organizationTree"})
    @ResponseBody
    public Object loadTreeNode(String id) {
        if (id == null)
            id = "NONE";
        try {
            return
                    EasyUiTreeNode.formatAsyncAjaxTree(
                            EasyUiTreeNode.queryTreeNodeOne(id, "SORT", "alone_auth_organization", "ID", "PARENTID",
                                    "NAME", "CTIME").getResultList(),
                            EasyUiTreeNode.queryTreeNodeTow(id, "SORT", "alone_auth_organization", "ID", "PARENTID", "NAME", "CTIME")
                                    .getResultList(), "PARENTID", "ID", "NAME", "CTIME");
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/organizationTreeAuth"})
    @ResponseBody
    public Object loadTreeNode(String id, HttpSession session) {
        boolean authFlag = false;
        Organization org = AuthUtils.getCurrentOrganization(session);
        if (id == null) {
            id = "NONE";
            if (org != null) {
                authFlag = true;
                id = org.getParentid();
            }
        }

        DataQuery query1 = EasyUiTreeNode.queryTreeNodeOneAuth(id, "SORT", "alone_auth_organization", "ID", "PARENTID",
                "NAME", "CTIME", null, null, authFlag);
        DataQuery query2 = EasyUiTreeNode.queryTreeNodeTowAuth(id, "SORT", "alone_auth_organization", "ID", "PARENTID",
                "NAME", "CTIME", null, authFlag);

        if (org != null) {
            query1.addRule(new DBRule("treecode", AuthUtils.getCurrentOrganization(session).getTreecode(), "like-"));
            query2.addRule(new DBRule("b.treecode", AuthUtils.getCurrentOrganization(session).getTreecode(), "like-"));
        }
        try {
            return EasyUiTreeNode.formatAsyncAjaxTree(query1.search().getResultList(), query2.search().getResultList(),
                    "PARENTID", "ID", "NAME", "CTIME");
        } catch (Exception e) {
            log.error(e.getMessage());
            return ViewMode.getInstance().setError(e.getMessage()).returnObjMode();
        }
    }

    @RequestMapping({"/loadTree"})
    @ResponseBody
    public List<Organization> loadTree() {
        return this.organizationServiceImpl.getTree();
    }

    @RequestMapping({"/loadPost"})
    @ResponseBody
    public List<Map<String, Object>> loadPost(String orgId) {
        return this.organizationServiceImpl.getPostList(orgId);
    }

    @RequestMapping({"/loadPostWithPOrgPost"})
    @ResponseBody
    public List<Map<String, Object>> loadPostWithPOrgPost(String orgId) {
        return this.organizationServiceImpl.getPostListWithPOrgPost(orgId);
    }
}